package cn.mijack.face;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import org.json.JSONException;
import org.json.JSONObject;

import cn.mijack.face.service.FaceService;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by MiJack on 2016/6/7.
 */

public class UploadImageActivity extends AppCompatActivity implements View.OnClickListener {
    final private int PICTURE_CHOOSE = 1;
    private String faceSetName = "starface";

    Button button1;
    Button button2;
    Button button3;
    Button button4;
    Button button5;
    Button button6;
    ImageView imageView;
    private static final String TAG = "UploadImageActivity";
    private ProgressDialog progressDialog;
    private Bitmap img;
    private String faceId;
    private String faceSetId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_image);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);
        button5 = (Button) findViewById(R.id.button5);
        button6 = (Button) findViewById(R.id.button6);
        imageView = (ImageView) findViewById(R.id.imageView);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        button3.setOnClickListener(this);
        button4.setOnClickListener(this);
        button5.setOnClickListener(this);
        button6.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //get a picture form your phone
        switch (v.getId()) {
            case R.id.button1:
                selectImage();
                break;
            case R.id.button2:
                uploadImage();
                break;
            case R.id.button3:
                add2FaceSet();
                break;
            case R.id.button4:
                recognitionSearch();
                break;
            case R.id.button5:
                createFaceSet();
            case R.id.button6:
                obtainFaceSet();
                break;
        }
    }


    private void selectImage() {
        Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
        photoPickerIntent.setType("image/*");
        startActivityForResult(photoPickerIntent, PICTURE_CHOOSE);
    }

    private void uploadImage() {
        if (img == null) {
            return;
        }
//                上传图片
        showProgressDialog();
        FaceService.uploadImage(img)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        showResultDialog(jsonObject.toString());
                        try {
                            JSONObject face = jsonObject.getJSONArray("face").getJSONObject(0);
                            faceId = face.getString("face_id");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        hideProgressDialog();
                    }
                });
    }


    private void add2FaceSet() {
        if (TextUtils.isEmpty(faceId)) {
            return;
        }
        Log.d(TAG, "faceId：" + faceId);

        FaceService.add2FaceSet(faceId, faceSetId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        showResultDialog(jsonObject.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        showResultDialog(e.getMessage());
                    }
                });

    }

    private void createFaceSet() {
        FaceService.createFaceSet(faceSetName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        try {
                            faceSetId = jsonObject.getString("faceset_id");
                            Log.d(TAG, "FACE_SET_NAME:" + faceSetId);
                            showResultDialog(jsonObject.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void obtainFaceSet() {
        FaceService.obtainFaceSet(faceSetName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        try {
                            faceSetId = jsonObject.getString("faceset_id");
                            Log.d(TAG, "FACE_SET_NAME:" + faceSetId);
                            showResultDialog(jsonObject.toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        showResultDialog(e.getMessage());
                    }
                });
    }


    private void recognitionSearch() {
        FaceService.recognitionSearch(faceId, faceSetId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JSONObject>() {
                    @Override
                    public void onNext(JSONObject jsonObject) {
                        showResultDialog(jsonObject.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        showResultDialog(e.getMessage());
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICTURE_CHOOSE) {
            if (data != null) {
                //The Android api ~~~
                String fileSrc = data.getDataString().substring("/file:".length() + 1);
                //Log.d(TAG, "Picture:" + fileSrc);
                //just read size
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;

                //scale size to read
                options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max((double) options.outWidth / 1024f, (double) options.outHeight / 1024f)));
                options.inJustDecodeBounds = false;
                img = BitmapFactory.decodeFile(fileSrc, options);
                imageView.setImageBitmap(img);
            } else {
                Log.d(TAG, "idButSelPic Photopicker canceled");
            }
        }
    }

    private void showProgressDialog() {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("上传分析中...");
            progressDialog.setCancelable(false);
        }
        progressDialog.show();
    }

    private void hideProgressDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.hide();
        }
    }

    private void showResultDialog(String string) {
        AlertDialog.Builder builder = new AlertDialog.Builder(UploadImageActivity.this);
        builder.setTitle("result").setMessage(string)
                .show();
    }

}
